import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/manufacturer',
      name: 'manufacturer',
      component: () => import('../views/ManufacturerView.vue'),
      meta: { requiresAuth: false, accountType: 'manufacturer' }
    },
    {
      path: '/seller',
      name: 'seller',
      component: () => import('../views/SellerView.vue'),
      meta: { requiresAuth: false, accountType: 'seller' }
    },
    
    {
      path: '/logistics',
      name: 'logistics',
      component: () => import('../views/LogisticsView.vue'),
      meta: { requiresAuth: false, accountType: 'logistics' }
    },
    {
      path: '/buyer',
      name: 'buyer',
      component: () => import('../views/BuyerView.vue'),
      meta: { requiresAuth: false, accountType: 'buyer' }
    },
    {
      path: '/admin',
      name: 'admin',
      component: () => import('../views/AdminView.vue'),
      meta: { requiresAuth: false, accountType: 'admin' }
    },
    {
      path: '/tx',
      name: 'tx',
      component: () => import('../views/tx.vue'),
      meta: { requiresAuth: false }
    },
  ],
})

// 修改路由守卫 - 允许未登录用户访问大类界面
router.beforeEach((to, from, next) => {
  // 从localStorage获取认证状态
  const accountId = localStorage.getItem('accountId')
  const accountType = localStorage.getItem('accountType')
  const isLoggedIn = !!accountId
  
  // 如果用户已登录但访问了不匹配的界面，显示提示
  if (isLoggedIn && to.meta.accountType && to.meta.accountType !== accountType) {
    alert('您没有权限访问此页面')
    next('/')
    return
  }
  
  // 允许所有用户访问所有页面，界面内部会处理登录状态
  next()
})

export default router